//
//  MyViewController.m
//  Hai
//
//  Created by 千金贷 on 16/2/23.
//  Copyright © 2016年 wangzijian. All rights reserved.
//

#import "LoginController.h"
#import "RegisterController.h"
#import "PwdController.h"
#import "Util.h"

@interface LoginController()<NSURLConnectionDataDelegate>
@property(nonatomic,strong)NSMutableData *responseData;
@end

@implementation LoginController{
    NSMutableURLRequest *request;
    UIAlertView    *alertView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
     _telView.layer.borderColor = ButtonGray.CGColor;
     _pwdView.layer.borderColor =ButtonGray.CGColor;
     self.navigationController.navigationBarHidden=NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; 
}


- (void)login{
    if (_tel.text.length==0) {
        [[[UIAlertView alloc] initWithTitle: @"请输入用户名" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    if (_pwd.text.length==0) {
        [[[UIAlertView alloc] initWithTitle: @"请输入密码" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    _loginButton.backgroundColor = ButtonGray;
    [_loginButton setEnabled:NO];
    NSString *pwdtext = [Util getMd5_32Bit_String:_pwd.text];
    
    [self.view endEditing:YES];//close keybox
    
    //第一步，创建url
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@login/login",BaseURL]];
    //第二步，创建请求
    NSString *postStr = [[NSString alloc] initWithFormat:@"account=%@&pw=%@",_tel.text,pwdtext];
    NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
    request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request addValue:[Util valueOfPlistKey:@"URL_VERSION" fileName:@"url"] forHTTPHeaderField:@"version"];
    //    NSDictionary *d = @{@"version":@"2"};
    //    [request setAllHTTPHeaderFields:d];
    [request setHTTPBody:postData];
    //第三步，连接服务器
    [self performSelector:@selector(connection) withObject:nil afterDelay:0.6];
    
}
-(void)connection{
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection == nil) {
        [[[UIAlertView alloc] initWithTitle: @"网络连接失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    [self showToast:@"正在登录"];//弹窗并禁止主线程操作
    
}

#pragma mark- NSURLConnectionDataDelegate代理方法
/*
 *当接收到服务器的响应（连通了服务器）时会调用
 */
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //NSLog(@"接收到服务器的响应");
    //初始化数据
    self.responseData=[NSMutableData data];
}

/*
 *当接收到服务器的数据时会调用（可能会被调用多次，每次只传递部分数据）
 */
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //NSLog(@"接收到服务器的数据");
    //拼接数据
    [self.responseData appendData:data];
}

/*
 *当服务器的数据加载完毕时就会调用
 */
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //NSLog(@"服务器的数据加载完毕");
    //隐藏HUD
    //[MBProgressHUD hideHUD];
    [_loginButton setEnabled:YES];
    _loginButton.backgroundColor = PinkColor;
    //处理服务器返回的所有数据
    NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];
    NSString *result=dict[@"code"];
    [self performSelectorOnMainThread:@selector(update) withObject:nil waitUntilDone:YES];
    if ([result isEqualToString:@"4000"]) {
        NSError *err;
        NSData *jsonObj = [dict[@"obj"] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonObj options:NSJSONReadingMutableContainers error:&err];
        NSData *jsonData = [data[@"member"] dataUsingEncoding:NSUTF8StringEncoding];
        NSData *jsonDataInfo = [data[@"memberInfo"] dataUsingEncoding:NSUTF8StringEncoding];
        
       
        NSDictionary *member = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
        [[NSUserDefaults standardUserDefaults] setObject:_tel.text forKey:MemberUserName];
        [[NSUserDefaults standardUserDefaults] setObject: member[@"member_id"] forKey:MemberID];
        [[NSUserDefaults standardUserDefaults] setObject: member[@"member_num"] forKey:@"member_num"];
        if (jsonDataInfo==nil) {
       
            [[NSUserDefaults standardUserDefaults] synchronize]; 
        }else{
            NSDictionary *memberInfo = [NSJSONSerialization JSONObjectWithData:jsonDataInfo options:NSJSONReadingMutableContainers error:&err];
            [[NSUserDefaults standardUserDefaults] setObject: memberInfo[@"member_provinces"] forKey:MemberProv];
            [[NSUserDefaults standardUserDefaults] setObject: memberInfo[@"member_city"] forKey:MemberCity];
             [[NSUserDefaults standardUserDefaults] setObject: memberInfo[@"member_birth"] forKey:@"member_birth"];
             [[NSUserDefaults standardUserDefaults] setObject: memberInfo[@"member_sex"] forKey:@"member_sex"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        
    }else if ([result isEqualToString:@"3100"]) {
        [[[UIAlertView alloc] initWithTitle: @"用户名或密码错误" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];//打开一个新的警告窗口
        //NSLog(@"%@",dict);
    }else{
        [[[UIAlertView alloc] initWithTitle: @"未知错误" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];//打开一个新的警告窗口
        //NSLog(@"%@",dict);
        
    }
    [self update];
}
/*
 *请求错误（失败）的时候调用（请求超时\断网\没有网\，一般指客户端错误）
 */
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //NSLog(@"请求错误");
    [self performSelectorOnMainThread:@selector(update) withObject:nil waitUntilDone:YES];
    [[[UIAlertView alloc] initWithTitle: @"网络异常" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
    [_loginButton setEnabled:YES];
    _loginButton.backgroundColor = PinkColor;
}



- (void)registerNew{
    RegisterController *va = [[RegisterController alloc] init];//初始化index控制器
    [self.navigationController pushViewController:va animated:YES];//跳转到首页
    //    HeadViewController *index = [[HeadViewController alloc] init];//初始化index控制器
    //    [self.navigationController pushViewController:index animated:YES];//跳转到首页
    //AccountViewController *index = [[AccountViewController alloc] init];//初始化index控制器
    //[self.navigationController pushViewController:index animated:YES];//跳转到首页
}

- (void)update{
    [self.indicator stopAnimating];
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
}

//弹出框
-(void)showToast:(NSString*) message{
    alertView = [[UIAlertView alloc] initWithTitle: message message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alertView show];
    self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.indicator.center = CGPointMake(alertView.bounds.size.width/2,alertView.bounds.size.height-40);
    self.indicator.hidesWhenStopped = YES;
    [alertView addSubview:self.indicator];
    [self.indicator startAnimating];
}



//点击空白隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
//点击enter隐藏键盘
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}
//在UITextField 编辑完成调用方法
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}

- (IBAction)zc{
    RegisterController *rp = [[RegisterController alloc] init];
    [self.navigationController pushViewController:rp animated:YES];
}
//找回密码
- (IBAction)wjmm{
    PwdController *rp = [[PwdController alloc] init];
    [self.navigationController pushViewController:rp animated:YES];
}
@end
